<template>
<!-- 消息列表页面 -->
  <div class="infoList">
    <div class="height_50"></div>
    <InfoHeader :userdata="userdata" class="InfoHeader" />
    <div class="content" id="content" ref="scroll">
      <InfoItem
        :otheruserdata="userdata"
        :info="item"
        class="contentitem"
        v-for="item in messagelist1"
        :key="item.id"
      />
    </div>

    <InfoFooter @sendMessage="sendMessage" class="InfoFooter" />
    <div class="height_50"></div>
  </div>
</template>

<script>
import InfoHeader from "@/components/info/InfoHeader";
import InfoFooter from "@/components/info/InfoFooter";
import InfoItem from "@/components/info/InfoItem";
import Time from "@/tool/time.js";

import {updatamessagemay} from "@/api/data"
export default {
  data() {
    return {
      messagelist: [],
      scrollTop: -80,
      contentHeight: 0,
      userdata: null,
      scrollTop: 0,
      timer: null,
    };
  },
  computed:{
    messagelist1(){
         if(this.$store.state.newmessage!=null && this.$store.state.newmessage.from_id==this.userdata._id){
              this.messagelist.push(this.$store.state.newmessage)
              this.$store.commit("removenewmessage")
              return this.messagelist
          }else{
            return this.messagelist
          }    
    }
  },
  mounted() {
    this.userdata = this.$route.query || null; // 获取当前的聊天对象的信息
    this.getallMessage();

    
    // 监听页面高度 滚动
  },
  updated() {
    // 同步高度
    let scrollHeight = this.$refs.scroll ? this.$refs.scroll.scrollHeight : 0;
    let clientHeight = this.$refs.scroll ? this.$refs.scroll.clientHeight : 0;

    this.$refs.scroll.scrollTop = scrollHeight - clientHeight;
  },
  destroyed() {
    // 销毁定时器
    this.timer = null;
  },
  components: {
    InfoHeader,
    InfoFooter,
    InfoItem,
  },
  methods: {
    // dingfshiqi1
    sleep(a = 100) {
      clearTimeout(this.timer);
      return new Promise((res) => {
        this.timer = setTimeout(() => {
          res();
        }, a);
      });
    },
    sendMessage(message) {
      let obj = {
        from_id: this.$store.state.userdata._id,
        to_id: this.userdata._id,
        content_text: message,
        content_img: "",
        time: Date.now(),
      };

      // 发送给他人
      this.$socket.emit("sendmsg", {
        msg: obj,
      });

      // 接受发送消息后的系统返回消息
      this.$socket.on("sendmsg", async (data) => {
        await this.sleep(500);
        this.messagelist.push(data.data);
        localStorage.setItem(
          `msglist-${this.$store.state.userdata._id}-${this.userdata._id}`,
          JSON.stringify(this.messagelist)
        );

        this.initdata(this.messagelist);
      });
    },

    // 获取所有消息
    getallMessage() {
      // 先获取本地的信息记录
      let msglist =
        JSON.parse(
          localStorage.getItem(
            `msglist-${this.$store.state.userdata._id}-${this.userdata._id}`
          )
        ) || [];
      // console.log(msglist)

      // 再获取远端与该用户没有阅读的信息
      this.$socket.emit("noread", {
        from_id: this.userdata._id,
        to_id: this.$store.state.userdata._id,
      });

      this.$socket.on("noread", (data) => {
        let arr2 = data.data;
        if (arr2.length > 0) {
          // 将获取回来的没有阅读的消息和本地消息合并
          this.messagelist = [...msglist, ...arr2];
          if(this.$store.state.newmessage!=null && this.$store.state.newmessage.from_id==this.userdata._id){
              this.messagelist.push(this.$store.state.newmessage)
          }

       
        } else {
          this.messagelist = msglist;
        }

        // 将所有消息存到本地
        localStorage.setItem(
          `msglist-${this.$store.state.userdata._id}-${this.userdata._id}`,
          JSON.stringify(this.messagelist)
        );

        if (this.messagelist.length > 0) {
          this.initdata(this.messagelist);
        }
      });
    },

    // 

    // 格式化最终的数据
    initdata(list) {
      for (let i = 0; i < list.length; i++) {
        if (i < list.length - 1) {
          list[i + 1].inittime = Time.gettime.getChatTime(
            list[i + 1].time,
            list[i].time
          );
        }
      }
      list[0].inittime = Time.gettime.gettime(list[0].time);

      this.messagelist = list;
    },
  },
};
</script>

<style lang="less" scoped>
.infoList {
  min-height: 100vh;
  width: 100vw;
  background-color: #f1f1f1;
}
.InfoHeader {
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
}
.InfoFooter {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 999;
}
.height_50 {
  height: 50px;
}
.content {
  height: calc(100vh - 100px);
  overflow: scroll;
}
</style>